﻿@{
    Layout = "_Layout";
    ViewData["Title"] = "资产信息管理";
}

<el-container>
    <avue-crud :data="tableData" :option="option" :permission="hasPermission" :page.sync="pageOption" :table-loading="loading"
               v-on:refresh-change="refreshChange"
               v-on:row-save="handleRowSave"
               v-on:row-update="handleRowUpdate"
               v-on:row-del="handleRowDel"
               v-on:search-change="searchChange"
               v-on:search-reset="resetChange"
               :cell-style="cellStyle"
               v-on:on-load="onLoad">
        <template slot="record" slot-scope="scope">
            <modify-record :data="scope.row"></modify-record>
        </template>
        <!-- 自定义操作列 -->
        <template slot="menu" slot-scope="scope">
            <el-button type="text" icon="el-icon-warning-outline" @@click ="showDisposeDialog(scope.row)"
                       v-if="scope.row.Status !== '已报废'">报废</el-button>
        </template>

        <!-- 折旧信息显示 -->
        <template slot="depreciationInfo" slot-scope="scope">
            <el-tag size="small">月折旧: {{scope.row.MonthlyDepreciation}}</el-tag>
            <el-tag size="small" type="success">累计折旧: {{scope.row.AccumulatedDepreciation}}</el-tag>
            <el-tag size="small" type="info">净值: {{scope.row.NetValue}}</el-tag>
        </template>
    </avue-crud>
    <!-- 资产报废对话框 -->
    <el-dialog title="资产报废" :visible.sync="disposeDialogVisible" width="30%">
        <el-form :model="disposeForm" label-width="100px">
            <el-form-item label="报废日期">
                <el-date-picker v-model="disposeForm.disposalDate" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="报废原因">
                <el-input v-model="disposeForm.reason" type="textarea" :rows="3"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @@click ="disposeDialogVisible = false">取消</el-button>
            <el-button type="primary" @@click ="handleDispose">确认</el-button>
        </span>
    </el-dialog>
</el-container>

@section Scripts {
    <script>
        new Vue({
            el: '#app',
            mixins: [curdMixin],
            data() {
                return {
                    name: "assets",
                    pageUrl: `/assets/pages`,
                    addUrl: `/assets/add`,
                    editUrl: `/assets/update`,
                    deleteUrl: `/assets/delete`,

                    option: {
                        searchShowBtn: Permissions.avePermission(`assets:searchBtn`),
                        refreshBtn: Permissions.avePermission(`assets:searchBtn`),
                        menuWidth: '350',
                        rowKey: 'id',
                        searchShow: false,
                        column: [
                            { prop: "id", label: `${this.i18n.t('primary_key')}`, search: false, hide: true, type: "number", display: false, showColumn: false },

                            // 基本信息
                            { prop: "code", label: `资产编码`, search: true, hide: false, width: '120', clearable: true, rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseenter')}` }] },
                            { prop: "name", label: `资产名称`, search: true, hide: false, width: '120', clearable: true, rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseenter')}` }] },

                            // 类型和规格
                            {
                                prop: "type",
                                label: `资产类型`,
                                search: true,
                                type: "select",
                                dicUrl: `/types/list`,
                                props: { label: "name", value: "id" },
                                rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseselect')}` }]
                            },
                            { prop: "specification", label: `规格型号`, search: false, hide: false, width: '120' },
                            { prop: "unit", label: `单位`, search: false, hide: false, width: '80', rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseenter')}` }] },

                            // 部门和位置
                            {
                                prop: "department",
                                label: `使用部门`,
                                search: true,
                                type: "select",
                                dicData: [
                                    { label: "财务部", value: "财务部" },
                                    { label: "人事部", value: "人事部" },
                                    { label: "技术部", value: "技术部" },
                                    { label: "市场部", value: "市场部" }
                                ],
                                rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseselect')}` }]
                            },
                            {
                                prop: "location",
                                label: `存放位置`,
                                search: true,
                                type: "select",
                                dicUrl: `/locations/list`,
                                props: { label: "name", value: "id" },
                                rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseselect')}` }]
                            },

                            // 日期信息
                            {
                                prop: "purchaseDate",
                                label: `购入日期`,
                                type: "date",
                                format: "yyyy-MM-dd",
                                valueFormat: "yyyy-MM-dd",
                                rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseselect')}` }]
                            },
                            {
                                prop: "depreciationStartDate",
                                label: `折旧开始日期`,
                                type: "date",
                                format: "yyyy-MM-dd",
                                valueFormat: "yyyy-MM-dd",
                                width: '110',
                                rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseselect')}` }]
                            },

                            // 财务信息
                            {
                                prop: "originalValue",
                                label: `资产原值`,
                                type: "number",
                                min: 0,
                                precision: 2,
                                rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseenter')}` }]
                            },
                            {
                                prop: "usefulLife",
                                label: `使用年限(年)`,
                                width: '110',
                                type: "number",
                                min: 1,
                                rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseenter')}` }]
                            },
                            {
                                prop: "residualRate",
                                label: `残值率(%)`,
                                type: "number",
                                min: 0,
                                max: 100,
                                precision: 2,
                                rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseenter')}` }]
                            },

                            // 计算字段（只读）
                            {
                                prop: "monthlyDepreciation",
                                label: `月折旧额`,
                                type: "number",
                                precision: 2,
                                display: false,
                                disabled: true
                            },
                            {
                                prop: "accumulatedDepreciation",
                                label: `累计折旧`,
                                type: "number",
                                precision: 2,
                                display: false,
                                disabled: true
                            },
                            {
                                prop: "depreciationYears",
                                label: `已折旧年限`,
                                width: '110',
                                type: "number",
                                display: false,
                                disabled: true
                            },
                            {
                                prop: "netValue",
                                label: `资产净值`,
                                type: "number",
                                precision: 2,
                                display: false,
                                disabled: true
                            },

                            // 状态信息
                            {
                                prop: "status",
                                label: `资产状态`,
                                search: true,
                                type: "select",
                                dicData: [
                                    { label: "在用", value: "在用" },
                                    { label: "闲置", value: "闲置" },
                                    { label: "维修中", value: "维修中" },
                                    { label: "报废", value: "报废" }
                                ],
                                value: "在用"
                            },

                            // 报废信息
                            {
                                prop: "disposalDate",
                                label: `报废日期`,
                                type: "date",
                                format: "yyyy-MM-dd",
                                valueFormat: "yyyy-MM-dd",
                                display: false
                            },
                            {
                                prop: "disposalReason",
                                label: `报废原因`,
                                type: "textarea",
                                span: 24,
                                display: false
                            },

                            // 修改记录
                            { prop: "record", label: `${this.i18n.t('modification_record')}`, slot: true, display: false, showColumn: false, width: 140, align: `center` }
                        ],
                    },

                    disposeDialogVisible: false,
                    disposeForm: {
                        assetId: null,
                        disposalDate: new Date(),
                        reason: ''
                    },
                    currentDisposeAsset: null,
                }
            },
            created() {
                this.selectRow = {};
            },
            methods: {
                cellStyle({ row, column }) {
                    if (column.property === 'status') {
                        switch(row.status) {
                            case '报废': return { color: '#f56c6c' };
                            case '维修中': return { color: '#e6a23c' };
                            case '闲置': return { color: '#909399' };
                            case '在用': return { color: '#67c23a' };
                            default: return {};
                        }
                    }
                },
                 showDisposeDialog(row) {
                    this.currentDisposeAsset = row;
                    this.disposeForm.assetId = row.id;
                    this.disposeForm.disposalDate = new Date();
                    this.disposeForm.reason = '';
                    this.disposeDialogVisible = true;
                },

                handleDispose(row) {
                    this.$http.post('/assets/dispose', {
                        AssetId: this.currentDisposeAsset.id,
                        DisposalDate: this.disposeForm.disposalDate,
                        Reason: this.disposeForm.reason
                    }).then(res => {
                        this.$message.success("资产已报废");
                        this.disposeDialogVisible = false;
                        this.refreshChange();
                    }).catch(err => {
                        this.$message.error(err.response?.data || "报废失败");
                    });
                },
                // handleRowSave(row, done, loading) {
                //     this.calculateDepreciation(row);
                //     this.$refs.crud.rowSave(row, done, loading);
                // },
                // handleRowUpdate(row, index, done, loading) {
                //     this.calculateDepreciation(row);
                //     this.$refs.crud.rowUpdate(row, index, done, loading);
                // },
                // calculateDepreciation(row) {
                //     if (row.originalValue && row.usefulLife && row.residualRate) {
                //         const residualValue = row.originalValue * (row.residualRate / 100);
                //         const depreciableAmount = row.originalValue - residualValue;

                //         // 计算月折旧额
                //         row.monthlyDepreciation = parseFloat((depreciableAmount / (row.usefulLife * 12)).toFixed(2));

                //         // 如果折旧开始日期已设置，计算累计折旧
                //         if (row.depreciationStartDate) {
                //             const startDate = new Date(row.depreciationStartDate);
                //             const now = new Date();
                //             const monthsDiff = (now.getFullYear() - startDate.getFullYear()) * 12 +
                //                             (now.getMonth() - startDate.getMonth());

                //             row.depreciationYears = Math.floor(monthsDiff / 12);
                //             row.accumulatedDepreciation = parseFloat(Math.min(
                //                 monthsDiff * row.monthlyDepreciation,
                //                 depreciableAmount
                //             )).toFixed(2);
                //             row.netValue = parseFloat(row.originalValue - row.accumulatedDepreciation).toFixed(2);
                //         }
                //     }
                // }
            }
        });
    </script>
}